import { gaode } from '@/config/projection/gaode';
// import * as ol from 'ol';
// import CoordinateConvert from "@/utils/proj/coordinate-convert";
import CoordinateConvert from '@/utils/proj/CoordinateConvert';
// import * as proj from "ol/proj";
import { proj4 } from '@/utils/proj/Proj4js';
import '@supermap/iclient-openlayers/index';
import { BaiduMap } from '@supermap/iclient-openlayers/mapping/BaiduMap';
// import { MapService } from '@supermap/iclient-openlayers/services/MapService';
// import { TileSuperMapRest } from '../TileSuperMapRest';
import { TileSuperMapRest } from '@supermap/iclient-openlayers/mapping/TileSuperMapRest';
import { getTopLeft, getWidth } from 'ol/extent';
import Point from 'ol/geom/Point';
import TileLayer from 'ol/layer/Tile';
import { get as getProjection } from 'ol/proj';
import WMTS from 'ol/source/WMTS';
import XYZ from 'ol/source/XYZ';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import View from 'ol/View';
import { createControl } from '../api/controls/MyControl';
import MapApi from '../api/index';
let app: MapApi;
export function start() {
    init();
    addMapEventListener();
    // SuperMapTest(app.map)
    // addCAD()
}

function SuperMapTest(map: any) {
    // //指定ID查询处理
    // const url = "http://support.supermap.com.cn:8090/iserver/services/data-world/rest/data";
    // //数据集ID查询服务参数
    // var idsParam = new SuperMap.GetFeaturesByIDsParameters({
    //     IDs: [246, 247],
    //     datasetNames: ["World:Countries"]
    // });
    // //向服务器发送请求，并获取结果
    // new FeatureService(url).getFeaturesByIDs(idsParam, function (serviceResult: any) {
    //     //获取返回的features数据
    //     console.log(serviceResult)
    //     var features = serviceResult.result.features;
    // });
    let map2d, urlWorld = 'http://support.supermap.com.cn:8090' + '/iserver/services/map-world/rest/maps/World',
        urlJinjing = 'http://support.supermap.com.cn:8090' + '/iserver/services/map-jingjin/rest/maps/京津地区人口分布图_专题图';
    // map = new ol.Map({
    //     target: 'map',
    //     controls: ol.control.defaults({ attributionOptions: { collapsed: false } })
    //         .extend([new ol.supermap.control.Logo()]),
    //     view: new ol.View({
    //         center: [116.85, 39.79],
    //         zoom: 7,
    //         projection: 'EPSG:4326'
    //     })
    // });
    // var worldLayer = new TileLayer({
    //     // source: new TileSuperMapRest({
    //     //     url: urlWorld
    //     // }),
    //     projection: 'EPSG:4326'
    // });
    // map.addLayer(worldLayer);
    // var jinJingLayer = new TileLayer({
    //     source: new TileSuperMapRest({
    //         url: urlJinjing,
    //         origin: [-180, 90],
    //         transparent: true
    //     }),
    //     projection: 'EPSG:4326'
    // });
    // map.addLayer(jinJingLayer);
}
function init() {
    // navigator.geolocation.getCurrentPosition(s => alert(s.coords.longitude + ',' + s.coords.latitude) , err => console.log(err));
    app = new MapApi({
        target: 'map',
        layers: [
            // new TileLayer({
            //     title: "高德地图卫星",
            //     source: new ol.source.AMap({mapType:"sat"})
            // })
            new TileLayer({
                // source: new BaiduMap ({
                // })
                source: new XYZ({
                    crossOrigin: 'anonymous',
                    minZoom: 2,
                    maxZoom: 20,
                    url: gaode.tile.url,
                    projection: 'EPSG:3857'
                    // url: `${iserverIP}/iserver/services/map-china400/rest/maps/China/zxyTileImage.png?z={z}&x={x}&y={y}`
                    // url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
                })
            })
        ],
        view: new View({
            center: proj4('EPSG:3857', CoordinateConvert.wgs2gcj([121.52464, 31.326378])),
            // center: CoordinateConvert().wgs2gcj(121.52464, 31.326378),
            // center: proj4("EPSG:3857", [121.52464, 31.326378]),
            // center: [121.52464, 31.326378],
            // center: [108.966808, 34.161176],
            zoom: 18,
            projection: 'EPSG:3857',
            // projection: 'EPSG:4326',
        })
        // new View({
        //     center:  proj.transform([121.4538, 34.465], 'EPSG:4326', 'GCJ02MC'),
        //     zoom: 7,
        //     projection: 'GCJ02MC'
        //   })
    });
}
// let listenerMap: Map<string, Array<Function>>
// function addEventListener(type: string, listener: ListenerFunction) {
//     app.map.addEventListener(type, listener)
//     if (listenerMap.has(type)) {
//         const maptemp = listenerMap.get(type);
//         maptemp && maptemp.push(listener)
//     } else {
//         listenerMap.set(type, [listener])
//     }
// }
function addMapEventListener() {

    // app.map.addControl(controlDefaults().extend([
    //     app.createControl()
    //   ]))
    app.map.addControl(createControl(buttonCB));
    const popup = app.createPopup();
    const element = popup.getElement();
    app.map.addOverlay(popup);

    app.map.addEventListener('click', (e: any) => {
        app.map.addLayer(app.addIconLayer({
            geometry: new Point(e.coordinate), name: 'Hello Island',
            population: 4000,
            rainfall: 500
        }));

        const feature = app.map.forEachFeatureAtPixel(e.pixel, feature => feature);
        if (feature) {
            const coordinates = (feature.getGeometry() as any).getCoordinates();
            popup.setPosition(coordinates);
            element.innerHTML = `${feature.get('name')}`;
            element.style.display = 'block';
        } else {
            element.style.display = 'node';
        }
    });
    app.map.on('pointermove', function(e: any) {
        if (e.dragging) {
            //   $(element).popover('destroy');
            return;
        }
        const pixel = app.map.getEventPixel(e.originalEvent);
        const hit = app.map.hasFeatureAtPixel(pixel);
        // console.log(e)
        // app.map.
        app.map.getTargetElement().style.cursor = hit ? 'pointer' : '';
        // e.target.viewport_.style.cursor = hit ? 'pointer' : '';
    });
    // app.map.addEventListener("click", (e: any) => console.log(proj4("EPSG:3857", "EPSG:4326", e.coordinate)))
}

const buttonCB = (e?: Event) => {
    console.log(e, 1);
};

// function addIcon(geometry: Coordinate) {
//     // console.log(app.map.getListeners("dbclick")[0])
//     var iconFeature = new Feature({
//         // geometry: new Point(proj4("EPSG:3857", [108.966808, 34.161176])),
//         geometry: new Point(geometry),
//         name: 'Null Island',
//         population: 4000,
//         rainfall: 500
//     });
//     var iconStyle = new Style({
//         image: new Icon({
//             anchor: [0.5, 46],
//             anchorXUnits: IconAnchorUnits.FRACTION,
//             anchorYUnits: IconAnchorUnits.PIXELS,
//             src: 'assets/icons/icon.png'
//         })
//     });

//     iconFeature.setStyle(iconStyle);

//     var vectorSource = new VectorSource({
//         features: [iconFeature]
//     });

//     var vectorLayer = new VectorLayer({
//         source: vectorSource
//     });
//     vectorLayer.on("click", e => console.log(e))
//     app.map.addLayer(vectorLayer)

// }
function addCAD() {
    const projection = getProjection('EPSG:3857');
    const projectionExtent = projection.getExtent();
    const size = getWidth(projectionExtent) / 256;
    // const matrixIds = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20' ];
    // const resolutions = [0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 0.0006866455078125, 0.00034332275390625, 0.000171661376953125, 0.0000858306884765625, 0.00004291534423828125, 0.000021457672119140625, 0.0000107288360595703125, 0.00000536441802978515625, 0.000002682209014892578125, 0.0000013411045074462890625];
    const resolutions = new Array(14);
    const matrixIds = new Array(14);
    for (let z = 0; z < 14; ++z) {
        // generate resolutions and matrixIds arrays for this WMTS
        resolutions[z] = size / Math.pow(2, z);
        matrixIds[z] = z;
    }

    // 新建图层
    const layer = new TileLayer({
        // source: new TileSuperMapRest({
        //     url: 'http://115.28.223.20:8090/iserver/services/map-ugcv5-GuanXianPeiTuShenPi2/wmts100',

        // })
        // source: new WMTS({
        //     // name: "World",
        //     url: "http://115.28.223.20:8090/iserver/services/map-ugcv5-GuanXianPeiTuShenPi2/wmts100",
        //     layer: '管线配图_审批',
        //     matrixSet: 'Custom_管线配图_审批',
        //     format: 'image/png',
        //     tileGrid: new WMTSTileGrid({
        //         // origin: [ -20037508.34,20037148.34],
        //         extent: [ -20037508.34 ,20037148.34 ,-20037148.34  ,20037508.34 ],
        //         // extent:[-2.0037508342787E7, -2.0037508342787E7,2.0037508342787E7, 2.0037508342787E7],
        //         resolutions: resolutions,
        //         matrixIds: matrixIds
        //     }),
        //     style: 'default',
        //     projection: projection
        // })
        source: new XYZ({
            crossOrigin: 'anonymous',
            minZoom: 2,
            maxZoom: 20,
            projection: 'EPSG:3857',
            url: 'http://115.28.223.20:8090/iserver/services/map-ugcv5-GuanXianPeiTuShenPi2/rest/maps/管线配图_审批/zxyTileImage.png?z={z}&x={x}&y={y}&width=256&height=256'
        })
    });
    // app.map.addLayer(layer)
    app.map.getLayers().insertAt(1, layer);
    console.log(app.map.getLayers());
}
